package com.taotao.content.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.taotao.common.pojo.EasyUITree;
import com.taotao.common.pojo.TaotaoResult;
import com.taotao.content.service.ContentCategoryService;
import com.taotao.mapper.TbContentCategoryMapper;
import com.taotao.pojo.TbContentCategory;
import com.taotao.pojo.TbContentCategoryExample;
import com.taotao.pojo.TbContentCategoryExample.Criteria;

/**
 * 内容分类管理service
 * <p>Title: ContentCategoryServiceImpl</p>
 * <p>Description: </p>
 * <p>Company: www.itcast.cn</p> 
 * @version 1.0
 */
@Service
public class ContentCategoryServiceImpl implements ContentCategoryService {

	@Autowired
	private TbContentCategoryMapper contentCategoryMapper;
	
	@Override
	public List<EasyUITree> getContentCategoryList(long parentId) {
		//根据parentId查询子节点列�?
		TbContentCategoryExample example = new TbContentCategoryExample();
		//设置查询条件
		Criteria criteria = example.createCriteria();
		criteria.andParentIdEqualTo(parentId);
		//执行查询
		List<TbContentCategory> list = contentCategoryMapper.selectByExample(example);
		List<EasyUITree> resultList = new ArrayList<>();
		for (TbContentCategory tbContentCategory : list) {
			EasyUITree node = new EasyUITree();
			node.setId(tbContentCategory.getId());
			node.setText(tbContentCategory.getName());
			node.setState(tbContentCategory.getIsParent()?"closed":"open");
			//添加到结果列�?
			resultList.add(node);
		}
		return resultList;
	}

	@Override
	public TaotaoResult createCategory(long parentId, String name) {
		TbContentCategory tbContentCategory=new TbContentCategory();
		tbContentCategory.setIsParent(false);
		tbContentCategory.setName(name);
		tbContentCategory.setParentId(parentId);
		
		tbContentCategory.setSortOrder(1);
		
		tbContentCategory.setStatus(1);
		tbContentCategory.setCreated(new Date());
		tbContentCategory.setUpdated(new Date());
		
		contentCategoryMapper.insert(tbContentCategory);
		
		TbContentCategory parentNode=contentCategoryMapper.selectByPrimaryKey(parentId);
		
		if(!parentNode.getIsParent()){
			parentNode.setIsParent(true);
			
			contentCategoryMapper.updateByPrimaryKey(parentNode);
			
		}
		return TaotaoResult.ok(tbContentCategory);
	}

	

}
